package com.zzk.minemodule.ui.mine;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.alibaba.android.arouter.launcher.ARouter;
import com.zzk.baselibrary.contract._Login;
import com.zzk.baselibrary.global.SPKeyGlobal;
import com.zzk.baselibrary.router.RoutePath;
import com.zzk.rxmvvmbase.base.BaseViewModel;
import com.zzk.rxmvvmbase.binding.command.BindingAction;
import com.zzk.rxmvvmbase.binding.command.BindingCommand;
import com.zzk.rxmvvmbase.bus.RxBus;
import com.zzk.rxmvvmbase.bus.RxSubscriptions;
import com.zzk.rxmvvmbase.utils.SPUtils;

import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;

/**
 *
 * @ProjectName: RXMVVMBaseComponent
 * @Package:
 * @ClassName:
 * @Description:
 * @Author: brilliantzhao
 * @CreateDate: 2021.1.14 9:39
 * @UpdateUser:
 * @UpdateDate: 2021.1.14 9:39
 * @UpdateRemark:
 * @Version: 1.0.0
 */
public class MineViewModel extends BaseViewModel {
    public ObservableInt loginBtnVisible = new ObservableInt();
    public ObservableField<String> userInfoObservable = new ObservableField();
    private Disposable subscribe;

    public MineViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    public void onCreate() {
        initData();
    }

    public void initData() {
        String userInfo = SPUtils.getInstance().getString(SPKeyGlobal.USER_INFO);
        if (!TextUtils.isEmpty(userInfo)) {
            userInfoObservable.set(userInfo);
            loginBtnVisible.set(View.GONE);
        } else {
            loginBtnVisible.set(View.VISIBLE);
        }
    }

    //登录按钮点击事件
    public BindingCommand startLoginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //采用ARouter+RxBus实现组件间通信
            ARouter.getInstance().build(RoutePath.SignModule.PAGE_LoginActivity).navigation();
            subscribe = RxBus.getDefault().toObservable(_Login.class)
                    .subscribe(new Consumer<_Login>() {
                        @Override
                        public void accept(_Login l) throws Exception {
                            //登录成功后重新刷新数据
                            initData();
                            //解除注册
                            RxSubscriptions.remove(subscribe);
                        }
                    });
            RxSubscriptions.add(subscribe);
        }
    });
    //退出登录按钮点击事件
    public BindingCommand outLoginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            SPUtils.getInstance().put(SPKeyGlobal.USER_INFO, "");
            initData();
        }
    });
}
